<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      v-if="!disabled && toolbarConfig"
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      class="editor"
      :class="{ disabled }"
      :style="{ height: disabled ? 'auto' : height }"
      v-model="valueHtml"
      :defaultConfig="Object.assign({ readOnly: disabled }, editorConfig)"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>
<script lang="ts" setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, shallowRef, watch, ref } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
const props = defineProps<{
  disabled?: boolean;
  value?: string;
  height?: number;
  mode?: "simple" | "default";
  toolbarConfig?: Record<string, any>;
  editorConfig?: Record<string, any>;
}>();
const emit = defineEmits<{ (event: "update:value", value: any): void }>();
// 内容 HTML
const valueHtml = ref(props.value);
watch(
  () => props.value,
  (val) => {
    valueHtml.value = val;
  }
);
watch(valueHtml, (val) => {
  emit("update:value", val);
});
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
</script>
<style lang="scss" scoped>
.editor {
  height: 500px;
  // eslint-disable-next-line prettier/prettier
  min-height: 300px;
  overflow-y: hidden;
  &.disabled {
    height: auto;
    min-height: auto;
  }
}
</style>
